<template>
  <div class="websocket-test-view">
    <AppHeader title="WebSocket测试" />

    <div class="websocket-test">
      <div id="main" style="width: 1200px; height: 800px;"></div>
      <div class="controls">
        <div class="input-group">
          <input id="text" v-model="message" type="text" placeholder="请输入要发送的消息" />
          <button @click="send">发送消息</button>
        </div>
        <button @click="closeWebSocket">关闭WebSocket连接</button>
      </div>
      <div class="status-bar">
        <span>连接状态：</span>
        <span :class="connectionStatus">{{ statusText }}</span>
      </div>
      <div id="message" class="message-container">
        <div class="message-header">消息记录：</div>
      </div>

      <!-- 任务提醒弹窗 -->
      <el-drawer
        v-model="showReminder"
        direction="btt"
        size="auto"
        :with-header="false"
        custom-class="reminder-drawer"
      >
        <div class="reminder-drawer-content">
          <div class="reminder-time">{{ formatTime(currentTask.expectedTime) }}</div>
          <div class="reminder-desc">{{ currentTask.description }}</div>
        </div>
        <div class="reminder-drawer-footer">
          <el-button @click="focusTask" type="primary" plain size="large">开始专注</el-button>
          <el-button @click="confirmReminder" type="primary" size="large">确认</el-button>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import AppHeader from '../components/AppHeader.vue'

export default {
  name: 'WebSocketTest',
  components: {
    AppHeader
  },
  data() {
    return {
      websocket: null,
      message: '',
      statusText: '未连接',
      connectionStatus: 'status-disconnected',
      showReminder: false,
      currentTask: {
        description: '',
        expectedTime: ''
      },
      connectionAttempts: 0,
      lastMessageTime: null,
      heartbeatInterval: null
    }
  },
  mounted() {
    console.log('组件已挂载，准备初始化WebSocket连接...')
    this.initWebSocket()
  },
  beforeUnmount() {
    console.log('组件即将卸载，准备关闭WebSocket连接...')
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
    }
    this.closeWebSocket()
  },
  methods: {
    initWebSocket() {
      console.log('开始初始化WebSocket连接...')
      if ('WebSocket' in window) {
        console.log('浏览器支持WebSocket，准备创建连接...')
        try {
          this.websocket = new WebSocket('ws://localhost:8080/api/websocket/100')
          console.log('WebSocket实例已创建，等待连接建立...', {
            readyState: this.websocket.readyState,
            CONNECTING: WebSocket.CONNECTING,
            OPEN: WebSocket.OPEN,
            CLOSING: WebSocket.CLOSING,
            CLOSED: WebSocket.CLOSED
          })
          
          this.heartbeatInterval = setInterval(() => {
            if (this.websocket.readyState === WebSocket.OPEN) {
              console.log('WebSocket连接状态检查:', {
                readyState: this.websocket.readyState,
                timestamp: new Date().toLocaleString()
              })
            }
          }, 5000)
          
          this.websocket.onerror = (error) => {
            console.error('WebSocket连接发生错误:', {
              error: error,
              timestamp: new Date().toLocaleString(),
              connectionAttempts: this.connectionAttempts,
              readyState: this.websocket.readyState
            })
            this.statusText = '连接错误'
            this.connectionStatus = 'status-error'
            this.setMessageInnerHTML('WebSocket连接发生错误')
          }

          this.websocket.onopen = () => {
            console.log('WebSocket连接已建立:', {
              timestamp: new Date().toLocaleString(),
              url: this.websocket.url,
              protocol: this.websocket.protocol,
              readyState: this.websocket.readyState,
              extensions: this.websocket.extensions
            })
            this.statusText = '已连接'
            this.connectionStatus = 'status-connected'
            this.setMessageInnerHTML('WebSocket连接成功')
            this.connectionAttempts = 0
          }

          this.websocket.onmessage = (event) => {
            const now = new Date()
            const timeSinceLastMessage = this.lastMessageTime ? 
              (now - this.lastMessageTime) / 1000 : '首次消息'
            
            console.log('收到WebSocket消息:', {
              rawData: event.data,
              timestamp: now.toLocaleString(),
              type: typeof event.data,
              timeSinceLastMessage: timeSinceLastMessage + '秒',
              readyState: this.websocket.readyState,
              messageSize: event.data.length,
              lastEventId: event.lastEventId,
              origin: event.origin,
              ports: event.ports
            })
            
            this.lastMessageTime = now
            this.setMessageInnerHTML('收到消息：' + event.data)
            this.handleTaskMessage(event.data)
          }

          this.websocket.onclose = (event) => {
            console.log('WebSocket连接已关闭:', {
              timestamp: new Date().toLocaleString(),
              code: event.code,
              reason: event.reason,
              wasClean: event.wasClean,
              readyState: this.websocket.readyState
            })
            this.statusText = '已断开'
            this.connectionStatus = 'status-disconnected'
            this.setMessageInnerHTML('WebSocket连接已关闭')
            
            if (this.heartbeatInterval) {
              clearInterval(this.heartbeatInterval)
            }
          }
        } catch (error) {
          console.error('创建WebSocket实例时发生错误:', error)
        }
      } else {
        console.error('当前浏览器不支持WebSocket')
        alert('当前浏览器不支持WebSocket')
      }
    },
    handleTaskMessage(message) {
      console.log('开始处理任务消息:', {
        message: message,
        timestamp: new Date().toLocaleString()
      })
      
      if (message.includes('任务提醒')) {
        try {
          console.log('检测到任务提醒消息，开始解析...')
          const parts = message.split('，')
          console.log('消息分割结果:', parts)
          
          const description = parts.find(part => part.includes('描述-'))?.split('描述-')[1]
          const expectedTime = parts.find(part => part.includes('预期时间-'))?.split('预期时间-')[1]
          
          console.log('解析结果:', {
            description: description,
            expectedTime: expectedTime,
            timestamp: new Date().toLocaleString()
          })

          if (description && expectedTime) {
            this.currentTask = {
              description,
              expectedTime
            }
            console.log('准备显示任务提醒弹窗:', this.currentTask)
            this.showReminder = true
          } else {
            console.warn('消息解析结果不完整:', {
              hasDescription: !!description,
              hasExpectedTime: !!expectedTime
            })
          }
        } catch (error) {
          console.error('解析任务消息失败:', {
            error: error,
            message: message,
            timestamp: new Date().toLocaleString()
          })
        }
      } else {
        console.log('非任务提醒消息，跳过处理')
      }
    },
    confirmReminder() {
      console.log('用户确认任务提醒:', {
        task: this.currentTask,
        timestamp: new Date().toLocaleString()
      })
      this.showReminder = false
      this.currentTask = {
        description: '',
        expectedTime: ''
      }
    },
    setMessageInnerHTML(innerHTML) {
      const messageDiv = document.getElementById('message')
      const messageElement = document.createElement('div')
      messageElement.className = 'message-item'
      messageElement.innerHTML = innerHTML
      messageDiv.appendChild(messageElement)
      messageDiv.scrollTop = messageDiv.scrollHeight
      
      console.log('消息已添加到显示区域:', {
        content: innerHTML,
        timestamp: new Date().toLocaleString()
      })
    },
    closeWebSocket() {
      if (this.websocket) {
        console.log('准备关闭WebSocket连接...')
        this.websocket.close()
        console.log('WebSocket关闭请求已发送')
      }
    },
    send() {
      if (this.websocket && this.message) {
        console.log('准备发送消息:', {
          message: this.message,
          timestamp: new Date().toLocaleString(),
          readyState: this.websocket.readyState
        })
        
        this.websocket.send('{"msg":"' + this.message + '"}')
        this.setMessageInnerHTML('发送消息：' + this.message)
        this.message = ''
      } else {
        console.warn('发送消息失败:', {
          hasWebSocket: !!this.websocket,
          hasMessage: !!this.message,
          timestamp: new Date().toLocaleString()
        })
      }
    },
    formatTime(timeStr) {
      if (!timeStr) return ''
      // 兼容 'Wed May 21 20:00:00 HKT 2025' 这类格式
      try {
        // 去掉时区（如 HKT），只保留前面的部分
        let cleanStr = timeStr.replace(/([A-Z]{3,4})/g, '').replace(/\s+/g, ' ').trim()
        // 兼容Safari，月份缩写要大写首字母
        const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
        months.forEach(m => {
          cleanStr = cleanStr.replace(new RegExp(m, 'i'), m)
        })
        const date = new Date(cleanStr)
        if (isNaN(date.getTime())) return ''
        const h = date.getHours().toString().padStart(2, '0')
        const m = date.getMinutes().toString().padStart(2, '0')
        return `${h}:${m}`
      } catch {
        return ''
      }
    },
    focusTask() {
      this.showReminder = false
      this.$router.push('/timer')
    }
  }
}
</script>

<style scoped>
.websocket-test-view {
  padding: 15px;
  padding-top: 60px; /* Add padding for the fixed header */
}

.websocket-test {
  padding: 20px;
}

.controls {
  margin: 20px 0;
}

.input-group {
  margin-bottom: 10px;
}

.input-group input {
  margin-right: 10px;
  padding: 8px;
  width: 300px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

button {
  padding: 8px 20px;
  margin-right: 10px;
  cursor: pointer;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
}

button:hover {
  background-color: #66b1ff;
}

.status-bar {
  margin: 10px 0;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.status-connected {
  color: #67c23a;
  font-weight: bold;
}

.status-disconnected {
  color: #909399;
}

.status-error {
  color: #f56c6c;
  font-weight: bold;
}

.message-container {
  margin-top: 20px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 100px;
  max-height: 300px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.message-header {
  font-weight: bold;
  margin-bottom: 10px;
  color: #606266;
}

.message-item {
  padding: 5px 0;
  border-bottom: 1px solid #ebeef5;
}

.reminder-drawer {
  border-radius: 16px 16px 0 0;
  min-height: 180px;
  max-width: 600px;
  margin: 0 auto;
  padding-bottom: env(safe-area-inset-bottom, 20px);
}
.reminder-drawer-content {
  padding: 32px 24px 16px 24px;
  text-align: left;
}
.reminder-time {
  color: #409eff;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}
.reminder-desc {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 24px;
  word-break: break-all;
}
.reminder-drawer-footer {
  display: flex;
  justify-content: space-between;
  padding: 0 24px 24px 24px;
  gap: 16px;
}
.reminder-drawer-footer .el-button {
  flex: 1;
  font-size: 18px;
  height: 48px;
}
@media (max-width: 600px) {
  .reminder-drawer {
    max-width: 100vw;
    min-width: 0;
    padding-left: 0;
    padding-right: 0;
  }
  .reminder-drawer-content, .reminder-drawer-footer {
    padding-left: 12px;
    padding-right: 12px;
  }
}
</style> 